<template>
  <view class="project-container" :style="{ paddingTop: totalNavHeight + 'px' }">
    <!-- 自定义导航栏 -->
    <CustomNavBar ref="navBarRef" :show-logo="true" />
    
    <!-- 加载动画 -->
    <view class="loading-mask" v-if="isLoading">
      <view class="loading-container">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载项目中...</text>
      </view>
    </view>
    
    <!-- 项目列表 -->
    <scroll-view 
      class="project-list" 
      v-show="!isLoading"
      :style="{ height: `calc(100vh - ${totalNavHeight}px)`, padding: '20rpx 30rpx' }"
      scroll-y="true"
      :show-scrollbar="false"
      enhanced="true"
      bounces="true"
      lower-threshold="100"
      @scrolltolower="loadMoreData"
      refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
  
      <view 
        class="project-card" 
        v-for="(project, index) in projectList" 
        :key="index"
        @tap="navigateToDetail(project['686df6df33681903aca1068e'])"
      >
      <!-- 项目名称 -->
        <view class="project-title">{{ project['686df5d4fa20ded33c042478']?.length > 15 ? project['686df5d4fa20ded33c042478']?.substring(0, 15) + '...' : project['686df5d4fa20ded33c042478'] }}</view>
        <view class="project-tags">
             <!-- 角色 -->
          <view 
            class="tag" 
            :class="getTagClass(tag.name)" 
            v-for="(tag, tagIndex) in JSON.parse(project['686e48ea1f42f2639e1b9074'])" 
            :key="tagIndex"
          >
            {{ tag.name }}
          </view>
        </view>
        <view class="project-info">
          <!-- 工作地点 -->
          <view class="info-item">
            <text class="iconfont icon-location"></text>
            <text class="info-text">{{ project['6876ff515d31544df2c58975'] }}</text>
          </view>
          <!-- 开始时间 / 天数 -->
          <view class="info-item">
            <text class="iconfont icon-calendar"></text>
            <text class="info-text">{{ project['686e317ee9211671b47589db'].slice(0, 10) }} | {{ project['68a2c8d3703512ca0fc1128c'] }}</text>
          </view>
        </view>
        <!-- 状态 -->
        <view 
          class="project-status" 
          :class="getStatusClass(project['686df6df33681903aca10690'])"
        >
          {{ project['686df6df33681903aca10690'] }}
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="load-more" v-if="!isLoading && projectList.length > 0">
        <view class="loading-more" v-if="isLoadingMore && hasMore">
          <view class="loading-spinner small"></view>
          <text class="loading-more-text">加载中...</text>
        </view>
        <view class="no-more" v-else-if="!hasMore && projectList.length > 0">
          <text class="no-more-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import { apiService, ApiService } from '/pages/utils/api.js'
import { useUserStore } from '/pages/store/user.js'
import CustomNavBar from '/pages/components/CustomNavBar.vue'

const userStore = useUserStore()

const platform = ref()

// 项目数据
const permission = ref(false)
const projectList = ref([])
const isLoading = ref(true)
const currentPage = ref(1)
const isLoadingMore = ref(false)  // 加载更多状态
const hasMore = ref(true)  // 是否还有更多数据
const loadMoreTimer = ref(null)  // 防抖定时器
const isRefreshing = ref(false) // 下拉刷新状态

// 导航栏组件引用
const navBarRef = ref(null)

// 计算总的导航栏高度（添加一些额外的间距）
const totalNavHeight = computed(() => {
  try {
    // 确保组件已挂载且存在
    if (navBarRef.value && navBarRef.value.totalNavHeight) {
      // totalNavHeight 是一个 computed，需要访问 .value
      const height = typeof navBarRef.value.totalNavHeight === 'object' 
        ? navBarRef.value.totalNavHeight.value 
        : navBarRef.value.totalNavHeight
      return height + 20  // 添加20px的间距
    }
    return 44 + 20  // 默认高度
  } catch (error) {
    console.warn('获取导航栏高度失败，使用默认值:', error)
    return 44 + 20  // 默认高度
  }
})

// 获取项目列表数据
const fetchProjectData = async (isLoadMore = false, isRefresh = false) => {
  try {
    if (isLoadMore) {
      isLoadingMore.value = true
    } else if (!isRefresh) {
      // 只有非刷新时才显示全屏加载遮罩
      isLoading.value = true
    }
    
    const data = await apiService.getFilterRows({
      worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
      pageIndex: currentPage.value
    })

    console.log('data');
    console.log(data);
    
    // 安全检查：确保data.rows存在且是数组
    const rows = data.rows || []
    
    //过滤未审核通过的
    const allowValues = ['招募中', '待补充', '报名中', '已完结'];
    const filteredData = rows.filter(
      item => item && allowValues.includes(item['686df6df33681903aca10690'])
    );

    if (isLoadMore) {
      // 加载更多时合并数据
      projectList.value = [...projectList.value, ...filteredData]
    } else {
      // 首次加载或刷新
      projectList.value = filteredData
    }

    // 根据当前页原始数据条数判断是否有更多数据
    hasMore.value = rows.length === 20

    console.log('==========');
    console.log('原始数据条数:', rows.length);
    console.log('过滤后数据条数:', filteredData.length);
    console.log('是否还有更多数据:', hasMore.value);
    console.log('当前总数据条数:', projectList.value.length);

  } catch (error) {
    console.error('获取项目数据失败:', error)
    // 错误已在request.js中统一处理，这里可以添加额外逻辑
  } finally {
    if (isLoadMore) {
      isLoadingMore.value = false
    } else if (!isRefresh) {
      // 只有非刷新时才隐藏全屏加载遮罩
      isLoading.value = false
    }
    // 如果是下拉刷新，需要重置刷新状态
    if (isRefreshing.value) {
      isRefreshing.value = false
    }
  }
}

// 触底加载更多
const loadMoreData = () => {
  console.log('触底加载更多触发', { hasMore: hasMore.value, isLoadingMore: isLoadingMore.value })
  
  // 防抖处理，避免频繁触发
  if (loadMoreTimer.value) {
    clearTimeout(loadMoreTimer.value)
  }
  
  loadMoreTimer.value = setTimeout(() => {
    if (!hasMore.value || isLoadingMore.value) {
      console.log('加载更多条件不满足，跳过')
      return
    }
    
    console.log('开始加载更多数据，当前页:', currentPage.value)
    currentPage.value++
    fetchProjectData(true)
  }, 300) // 300ms防抖
}

// 下拉刷新事件
const onRefresh = () => {
  console.log('下拉刷新触发');
  isRefreshing.value = true; // 设置刷新状态
  currentPage.value = 1; // 刷新时重置页码
  hasMore.value = true; // 确保有更多数据
  fetchProjectData(false, true); // 刷新数据
}

// 检测平台
const checkPlatform = () => {
  try {
     const { uniPlatform } = uni.getSystemInfoSync();
    console.log('platform', uniPlatform);
    
    platform.value = uniPlatform
    
    // 根据平台执行不同逻辑
    if (uniPlatform === 'mp-weixin') {
      console.log('当前运行在微信小程序')
      // 微信小程序特定逻辑
    } else if (uniPlatform === 'app') {
      console.log('当前运行在APP端')
      // APP端特定逻辑
    } else if (uniPlatform === 'h5') {
      console.log('当前运行在H5端')
      // H5端特定逻辑
    }
  } catch (error) {
    console.error('获取系统信息失败:', error)
  }
}

const getUserInfo = async () => {
 const localUserInfo = uni.getStorageSync('userInfo')
 if(localUserInfo){
  userStore.initUserState()
  userStore.isLogin = true
   // 直接从API获取最新用户信息，不使用本地缓存
    console.log('从API获取最新用户信息')
    console.log('userStore.rowid', userStore.rowid);
    
    const response = await apiService.getUserInfo(userStore.rowid)

    if(response && response.rows && response.rows.length > 0) {
    
    const apiUserInfo = response.rows[0]
    console.log('API获取的用户信息:', apiUserInfo)
    
    // 将用户信息存储到本地
    uni.setStorageSync('userInfo', apiUserInfo)
    console.log('用户信息已存储到本地')

    userStore.updateUserInfo(apiUserInfo)
    }
 }else{
   console.log('本地没有用户信息，未登录')
 }

}

// 页面加载时调用API
onLoad((options) => {
  fetchProjectData()
  checkPlatform()
  getUserInfo()
  console.log('项目页面加载完成', options)
  
})

// 滚动到底部加载更多 (现在通过scroll-view的@scrolltolower事件处理)

// 跳转到职位详情页面
const navigateToDetail = (id) => {
  if(!userStore.isLogin){
    uni.showToast({
      title: '您暂未登录，无权限查看 ',
      icon: 'none'
    })
    return
  }
  console.log('权限', userStore.userInfo['68be772ad829c4f4b8a809e5']);
  
  if(userStore.userInfo['68be772ad829c4f4b8a809e5'] == '游客'){
     uni.showToast({
      title: '您暂无权限查看 ',
      icon: 'none'
    })
    return
  }
  uni.navigateTo({
    url: `/pages/tabs/project/detail/position?id=${id}`
  })
}

// 根据标签获取对应的样式类名
const getTagClass = (tag) => {
  const tagClassMap = {
    '礼仪': 'tag-ceremony',
    '兼职': 'tag-parttime',
    '带队': 'tag-leader',
    '试驾': 'tag-testdrive',
    '发布会': 'tag-launch',
    '接待': 'tag-reception',
    '会议': 'tag-meeting',
    '服务': 'tag-service'
  }
  return tagClassMap[tag] || ''
}

// 根据状态获取对应的样式类名
const getStatusClass = (status) => {
  const statusClassMap = {
    '招募中': 'recruiting',
    '待补充': 'supplement',
    '报名中': 'applying',
    '已完结': 'completed'
  }
  return statusClassMap[status] || ''
}
</script>

<style scoped>
/* 自定义导航栏样式已迁移到 CustomNavBar 组件 */

.project-list{
  padding-top: 40rpx;
  box-sizing: border-box;
  /* 高度通过内联样式动态设置 */
}

/* 隐藏滚动条样式 */
.project-list ::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
}

.project-list {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

/* 加载动画样式 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-container {
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 48rpx 64rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.loading-spinner {
  width: 64rpx;
  height: 64rpx;
  border: 6rpx solid #F0F0F0;
  border-top: 6rpx solid #FF6B9B;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 24rpx;
}

.loading-spinner.small {
  width: 32rpx;
  height: 32rpx;
  border-width: 3rpx;
  margin-bottom: 0;
  margin-right: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 加载更多样式 */
.load-more {
  padding: 40rpx 0 60rpx 0; /* 增加底部间距 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-more-text {
  font-size: 28rpx;
  color: #999999;
}

.no-more {
  text-align: center;
}

.no-more-text {
  font-size: 28rpx;
  color: #999999;
}

/* 项目列表页面样式 */
.project-container {
/*  height: 100vh;
  overflow: hidden; */
  background-color: #f5f5f5;
  /* 去掉所有padding，让scroll-view独占空间 */
  /* padding-top通过computed动态设置，不再使用固定值 */
}

/* 页面级样式 */
page {
  background-color: #f5f5f5;
}

/* 项目卡片样式 */
.project-card {
  position: relative;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

/* 点击态样式 */
.project-card:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

/* 项目标题 */
.project-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80%;
}

/* 项目标签容器 */
.project-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

/* 标签基础样式 */
.tag {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 30rpx;
  margin-right: 16rpx;
  margin-bottom: 10rpx;
  color: #333; /* 将所有标签文字颜色修改为黑色 */
}

/* 礼仪标签 - 粉色 */
.tag-ceremony {
  background-color: rgba(255, 107, 155, 0.1);
}

/* 兼职标签 - 蓝色 */
.tag-parttime {
  background-color: rgba(62, 123, 250, 0.1);
}

/* 带队标签 - 橙色 */
.tag-leader {
  background-color: rgba(255, 154, 62, 0.1);
}

/* 试驾标签 - 绿色 */
.tag-testdrive {
  background-color: rgba(46, 204, 113, 0.1);
}

/* 发布会标签 - 紫色 */
.tag-launch {
  background-color: rgba(155, 89, 182, 0.1);
}

/* 接待标签 - 青色 */
.tag-reception {
  background-color: rgba(26, 188, 156, 0.1);
}

/* 会议标签 - 棕色 */
.tag-meeting {
  background-color: rgba(211, 84, 0, 0.1);
}

/* 服务标签 - 灰色 */
.tag-service {
  background-color: rgba(149, 165, 166, 0.1);
}

/* 项目信息区域 */
.project-info {
  display: flex;
  flex-direction: column;
}

/* 信息项 */
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

/* 图标样式 - 使用伪元素替代实际图标 */
.iconfont {
  width: 30rpx;
  height: 30rpx;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-location::before {
  content: "📍";
  font-size: 24rpx;
}

.icon-calendar::before {
  content: "📅";
  font-size: 24rpx;
}

/* 信息文本 */
.info-text {
  font-size: 24rpx;
  color: #999;
}

/* 项目状态标签 */
.project-status {
  position: absolute;
  top: 30rpx;
  right: 30rpx;
  padding: 8rpx 20rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
  font-weight: 500;
}

/* 招募中状态 */
.recruiting {
  background-color: #f0529d;
  color: #fff;
}

/* 待补充状态 */
.supplement {
  background-color: #fe7801;
  color: #fff;
}

/* 报名中状态 */
.applying {
  background-color: #9e6cf3;
  color: #fff;
}

/* 已完结状态 */
.completed {
  background-color: #747474;
  color: #fff;
}
</style>